package cn.dgut.training.controller;

import cn.dgut.training.entity.Admin;
import cn.dgut.training.service.impl.AdminServiceImpl;
import cn.dgut.training.util.JacksonUtil;
import cn.dgut.training.vo.CommonResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/profile")
@Validated
public class ProfileController {

    private final Log logger = LogFactory.getLog(ProfileController.class);

    @Resource
    private AdminServiceImpl adminService;

    @RequiresAuthentication
    @PostMapping("/password")
    public CommonResponse create(@RequestBody String body) {
        String oldPassword = JacksonUtil.parseString(body, "oldPassword");
        String newPassword = JacksonUtil.parseString(body, "newPassword");
        if (StringUtils.isEmpty(oldPassword)) {
            return CommonResponse.fail(401, "参数不对");
        }
        if (StringUtils.isEmpty(newPassword)) {
            return CommonResponse.fail(401, "参数不对");
        }

        Subject currentUser = SecurityUtils.getSubject();
        Admin admin = (Admin) currentUser.getPrincipal();

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (!encoder.matches(oldPassword, admin.getPassword())) {
            return CommonResponse.fail(605, "账号密码不对");
        }

        String encodedNewPassword = encoder.encode(newPassword);
        admin.setPassword(encodedNewPassword);

        adminService.updateById(admin);
        return CommonResponse.message();
    }

}
